package com.basin.common.mybatisplus.base;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.basin.common.core.response.Resp;
import com.basin.common.core.validate.ValidateGroup;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.List;

/**
 * @author: Sam ZHONG | sammy1997@aliyun.com
 */
public abstract class BaseController<DTO, VO,
        SERVICE extends BaseService<DTO, VO>> {
    protected SERVICE service;

    @Resource
    public void setService(SERVICE service) {
        this.service = service;
    }

    @PostMapping("/save")
    @Operation(summary = "新增")
    public Resp<Boolean> save(@RequestBody
                              @Validated(value = {ValidateGroup.Add.class}) DTO dto) {
        boolean success = this.service.save(dto);
        return success ? Resp.success() : Resp.fail();
    }

    @PostMapping("/save-batch")
    @Operation(summary = "批量新增")
    public Resp<Boolean> save(@RequestBody
                              @Validated(value = {ValidateGroup.Add.class}) List<DTO> dtoList) {
        boolean success = this.service.saveBatch(dtoList);
        return success ? Resp.success() : Resp.fail();
    }

    @PutMapping("/update")
    @Operation(summary = "更新")
    public Resp<Boolean> update(@RequestBody
                                @Validated(value = {ValidateGroup.Update.class}) DTO dto) {
        boolean success = this.service.update(dto);
        return success ? Resp.success() : Resp.fail();
    }

    @PutMapping("/update-batch")
    @Operation(summary = "批量更新")
    public Resp<Boolean> updateBatch(@RequestBody
                                     @Validated(value = {ValidateGroup.Update.class}) List<DTO> dtoList) {
        boolean success = this.service.updateBatch(dtoList);
        return success ? Resp.success() : Resp.fail();
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除")
    public Resp<Boolean> delete(@RequestBody Long id) {
        boolean success = this.service.delete(id);
        return success ? Resp.success() : Resp.fail();
    }

    @DeleteMapping("/delete-batch")
    @Operation(summary = "批量删除")
    public Resp<Boolean> deleteBatch(@RequestBody Collection<Long> idList) {
        boolean success = this.service.deleteBatch(idList);
        return success ? Resp.success() : Resp.fail();
    }

    @PostMapping("/page")
    @Operation(summary = "分页查询")
    public Resp<IPage<VO>> page(@RequestBody DTO dto) {
        IPage<VO> page = this.service.page(dto);
        return Resp.success(page);
    }

    @GetMapping("/detail/{id}")
    @Operation(summary = "获取详情")
    public Resp<VO> detail(@PathVariable(name = "id") Long id) {
        VO detail = this.service.detail(id);
        return Resp.success(detail);
    }
}
